/**
 * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
 *
 * This library is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Lesser General Public License as published by the Free
 * Software Foundation; either version 2.1 of the License, or (at your option)
 * any later version.
 *
 * This library is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
 * details.
 */

package com.cmc.service.merchant.service.impl;

import java.util.Date;
import java.util.Locale;

import com.cmc.service.merchant.AgentEntryDuplicateCodeException;
import com.cmc.service.merchant.AgentEntryHasInvalidFieldException;
import com.cmc.service.merchant.AgentEntryNotEnoughRequiredFieldsException;
import com.cmc.service.merchant.NoSuchAgentEntryException;
import com.cmc.service.merchant.model.AgentEntry;
import com.cmc.service.merchant.service.base.AgentEntryLocalServiceBaseImpl;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.util.Validator;
import com.liferay.portal.model.User;
import com.liferay.portal.service.ServiceContext;

/**
 * The implementation of the agent entry local service.
 * 
 * <p>
 * All custom service methods should be put in this class. Whenever methods are
 * added, rerun ServiceBuilder to copy their definitions into the
 * {@link com.cmc.service.merchant.service.AgentEntryLocalService} interface.
 * 
 * <p>
 * This is a local service. Methods of this service will not have security
 * checks based on the propagated JAAS credentials because this service can only
 * be accessed from within the same VM.
 * </p>
 * 
 * @author ntcuong1
 * @see com.cmc.service.merchant.service.base.AgentEntryLocalServiceBaseImpl
 * @see com.cmc.service.merchant.service.AgentEntryLocalServiceUtil
 */
public class AgentEntryLocalServiceImpl extends AgentEntryLocalServiceBaseImpl {
	/*
	 * NOTE FOR DEVELOPERS:
	 * 
	 * Never reference this interface directly. Always use {@link
	 * com.cmc.service.merchant.service.AgentEntryLocalServiceUtil} to access
	 * the agent entry local service.
	 */
	
	
	/**
	 * Add agentEntry and add new User belong to this agent.
	 * 
	 * @param userId creator userId
	 * @param password password for user (if agentEntry.isLoginable())
	 * @param verifyPassword veriryPassword for user (if agentEntry.isLoginable())
	 * @param locale locale of this user
	 * @param groupIds groupIds (sites) which user belong to
	 * @param organizationIds organization which user belong to
	 * @param roleIds roles of this user
	 * @param userGroupIds groups of this user
	 * @param sendEmail  
	 * @param agentEntry
	 * @param serviceContext
	 * @return
	 * @throws SystemException if a system error occured
	 * @throws PortalException if agent's not enougnt required fields, fields is not correct,
	 * there was agent existing with this code.
	 */
	public AgentEntry addAgent(long userId, String password, String verifyPassword, 
			Locale locale, long[] groupIds, long[] organizationIds, 
			long[] roleIds, long[] userGroupIds, boolean sendEmail, 
			AgentEntry agentEntry,ServiceContext serviceContext) 
						throws SystemException, PortalException {
		//validation fields
		validateFields(agentEntry);
		
		//validate unique code field
		try {
			AgentEntry a = agentEntryPersistence.findByCode(agentEntry.getCode());
			
			if (a != null) 
				throw new AgentEntryDuplicateCodeException();
		
		} catch (NoSuchAgentEntryException ex) {
			//true case
		}
		
		//create user
		if (agentEntry.isLoginable()) {
			User user = userLocalService.addUser(userId,
												agentEntry.getCompanyId(), 
												false, 
												password, 
												verifyPassword, 
												false, 
												agentEntry.getScreenName(), 
												agentEntry.getEmail(), 
												0, 
												null, 
												locale, 
												agentEntry.getFirstName(),
												agentEntry.getMiddleName(), 
												agentEntry.getLastName(), 
												agentEntry.getPrefixId(), 
												agentEntry.getSuffixId(), 
												agentEntry.isMale(), 
												agentEntry.getBirthdayMonth(), 
												agentEntry.getBirthdayDay(), 
												agentEntry.getBirthdayYear(), 
												agentEntry.getJobTitle(), 
												groupIds, 
												organizationIds, 
												roleIds, 
												userGroupIds, 
												sendEmail, 
												serviceContext);
			
			agentEntry.setUserId(user.getUserId());
		}	
		
		Date currentDate = new Date();
		
		AgentEntry agent = agentEntryPersistence.create(counterLocalService
				.increment(AgentEntry.class.getName()));
		
		agent.setCreatorUserId(userId);
		agent.setCompanyId(agentEntry.getCompanyId());
		agent.setCreateDate(currentDate);
		agent.setModifiedDate(currentDate);
		
		agent.setType(agentEntry.getType());
		agent.setCode(agentEntry.getCode());
		agent.setFirstName(agentEntry.getFirstName());
		agent.setLastName(agentEntry.getLastName());
		agent.setMiddleName(agentEntry.getMiddleName());
		agent.setPrefixId(agentEntry.getPrefixId());
		agent.setSuffixId(agentEntry.getSuffixId());
		agent.setMale(agentEntry.isMale());
		agent.setBirthdayDay(agentEntry.getBirthdayDay());
		agent.setBirthdayMonth(agentEntry.getBirthdayMonth());
		agent.setBirthdayYear(agentEntry.getBirthdayYear());
		agent.setJobTitle(agentEntry.getJobTitle());
		agent.setEmail(agentEntry.getEmail());
		agent.setMerchantId(agentEntry.getMerchantId());
		agent.setLoginable(agentEntry.isLoginable());
		agent.setUserId(agentEntry.getUserId());
		agent.setScreenName(agentEntry.getScreenName());
		
		return agent;
	}
	
	@Override
	public AgentEntry deleteAgentEntry(long agentId) throws SystemException, PortalException {		
		AgentEntry agent = agentEntryPersistence.findByPrimaryKey(agentId);
		
		if (Validator.isNotNull(agent.getUserId())) {
			userLocalService.deleteUser(agent.getUserId());
		}
		
		return agentEntryPersistence.remove(agentId);
	}
	
	public void validateFields(AgentEntry agent) throws PortalException { 
		if (Validator.isNull(agent.getCompanyId()))
			throw new AgentEntryNotEnoughRequiredFieldsException("companyId");
		if (Validator.isNull(agent.getFirstName())) 
			throw new AgentEntryNotEnoughRequiredFieldsException("firstName");
		if (Validator.isNull(agent.getType()))
			throw new AgentEntryNotEnoughRequiredFieldsException("type");
		if (Validator.isNull(agent.getCode()))
			throw new AgentEntryNotEnoughRequiredFieldsException("code");
		if (Validator.isName(agent.getEmail()))
			throw new AgentEntryNotEnoughRequiredFieldsException("email");
		if (!Validator.isEmailAddress(agent.getEmail()))
			throw new AgentEntryHasInvalidFieldException("email");
	}
}